/**
 * 
 */
package group.anglers.bpmn.core.runtime;

import group.anglers.om.core.persistence.Persistence;

import java.io.InputStream;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;

/**
 * @author an.pham
 * 
 */
@Singleton
@Startup
public class RuntimeEnvironment {
	private Logger logger = Logger.getLogger(RuntimeEnvironment.class.getName());
	
	private static final String DEFAULT_DIR = "META-INF/default/";
	private static final String DEFAULT_TABLES_FILE = DEFAULT_DIR + "tables.sql";

	@Inject
	private Persistence persistence;

	@PostConstruct
	public void init() {
		dbInit();
	}

	private void dbInit() throws RuntimeException {
		logger.info("Initializing Angler BPMN database ...");

		InputStream inputStream = getClass().getClassLoader().getResourceAsStream(DEFAULT_TABLES_FILE);
		
		try {
			try {
				persistence.executeBatch(inputStream);
			} finally {
				if (inputStream != null) {
					inputStream.close();
				}
				
				persistence.flush();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
